#include "chat_message.h"

#include <boost/asio.hpp>

#include <deque>
#include <set>

using boost::asio::ip::tcp;

using chat_message_queue = std::deque<chat_message>;

class chat_session;
using chat_session_ptr = std::shared_ptr<chat_session>;

// 聊天室类的声明
class chat_room {
    public:

        void join(chat_session_ptr);
        void leave(chat_session_ptr);
        void deliver(const chat_message&);
    private:
        std::set<chat_session_ptr> participants_;
        enum { max_recent_msgs = 100 };
        chat_message_queue recent_msgs_;
};



class chat_session: public std::enable_shared_from_this<chat_session> {//继承自共享类
    public:
        chat_session(tcp::socket socket, chat_room& room);

        void start();

        void deliver(const chat_message& msg);
    private:
        // 读取消息头
        void do_read_header();


        void do_read_body();


        void do_write();

        tcp::socket socket_;
        // room的生命周期必须长于session的生命周期，
        // 否则会因为持有无效的引用而翻车
        chat_room& room_;
        chat_message read_msg_;
        chat_message_queue write_msgs_;
};



class chat_server{
    public:
    chat_server(boost::asio::io_service& io_service, 
                    const tcp::endpoint& endpoint);
    void do_accept();
    private:
    tcp::acceptor acceptor_;
    tcp::socket socket_;
    chat_room room_;
};